package com.york.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.york.api.common.ErrorCode;
import com.york.api.constant.CommonConstant;
import com.york.api.exception.BusinessException;
import com.york.api.exception.ThrowUtils;
import com.york.api.mapper.InterfaceInfoMapper;
import com.york.api.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.york.api.model.entity.*;
import com.york.api.model.vo.InterfaceInfoVO;
import com.york.api.model.vo.UserVO;
import com.york.api.service.InterfaceInfoService;
import com.york.api.service.UserService;
import com.york.api.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author York
 * @description 针对表【interface_info(接口信息)】的数据库操作Service实现
 * @createDate 2024-11-26 15:47:19
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
        implements InterfaceInfoService {

    @Resource
    private UserService userService;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 校验接口信息
     *
     * @param interfaceInfo
     * @param add
     */
    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = interfaceInfo.getName();
        String url = interfaceInfo.getUrl();
        String requestParams = interfaceInfo.getRequestParams();
        String requestHeader = interfaceInfo.getRequestHeader();
        String responseHeader = interfaceInfo.getResponseHeader();
        String method = interfaceInfo.getMethod();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(name, url, requestParams, requestHeader, responseHeader, method),
                    ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(name) && name.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口名称过长");
        }
        if (StringUtils.isNotBlank(url) && url.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口URL过长");
        }
        if (StringUtils.isNotBlank(requestParams) && requestParams.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口请求参数过长");
        }
        if (StringUtils.isNotBlank(requestHeader) && requestHeader.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口请求头过长");
        }
        if (StringUtils.isNotBlank(responseHeader) && responseHeader.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口响应头过长");
        }
        if (StringUtils.isNotBlank(method) && method.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口请求方法过长");
        }


    }


    /**
     * 获取查询包装类
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<InterfaceInfo> getQueryWrapper(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        if (interfaceInfoQueryRequest == null) {
            // 如果查询对象为 null，默认返回所有数据
            return queryWrapper;
        }

        // 动态构建查询条件（“或”关系）
        queryWrapper.lambda()
                .or(StringUtils.isNotBlank(interfaceInfoQueryRequest.getName()),
                        wrapper -> wrapper.like(InterfaceInfo::getName, interfaceInfoQueryRequest.getName()))
                .or(StringUtils.isNotBlank(interfaceInfoQueryRequest.getDescription()),
                        wrapper -> wrapper.like(InterfaceInfo::getDescription, interfaceInfoQueryRequest.getDescription()))
                .or(StringUtils.isNotBlank(interfaceInfoQueryRequest.getUrl()),
                        wrapper -> wrapper.like(InterfaceInfo::getUrl, interfaceInfoQueryRequest.getUrl()))
                .or(StringUtils.isNotBlank(interfaceInfoQueryRequest.getMethod()),
                        wrapper -> wrapper.eq(InterfaceInfo::getMethod, interfaceInfoQueryRequest.getMethod()))
                .or(StringUtils.isNotBlank(interfaceInfoQueryRequest.getRequestParams()),
                        wrapper -> wrapper.like(InterfaceInfo::getRequestParams, interfaceInfoQueryRequest.getRequestParams()))
                .or(StringUtils.isNotBlank(interfaceInfoQueryRequest.getRequestHeader()),
                        wrapper -> wrapper.like(InterfaceInfo::getRequestHeader, interfaceInfoQueryRequest.getRequestHeader()))
                .or(StringUtils.isNotBlank(interfaceInfoQueryRequest.getResponseHeader()),
                        wrapper -> wrapper.like(InterfaceInfo::getResponseHeader, interfaceInfoQueryRequest.getResponseHeader()))
                .or(interfaceInfoQueryRequest.getStatus() != null,
                        wrapper -> wrapper.eq(InterfaceInfo::getStatus, interfaceInfoQueryRequest.getStatus()))
                .and(interfaceInfoQueryRequest.getIsDelete() != null,
                        wrapper -> wrapper.eq(InterfaceInfo::getIsDelete, interfaceInfoQueryRequest.getIsDelete()));

        // 排序
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        if (SqlUtils.validSortField(sortField)) {
            queryWrapper.orderBy(true, CommonConstant.SORT_ORDER_ASC.equals(sortOrder), sortField);
        }

        return queryWrapper;
    }


    /**
     * 封装ES查询条件(后续补充)
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @Override
    public Page<InterfaceInfo> searchFromEs(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        return null;
    }


    /**
     * 获取VO信息
     * v1:不涉及任何复杂业务，只是实现查询得到结果
     *
     * @param interfaceInfo
     * @param request
     * @return
     */
    @Override
    public InterfaceInfoVO getInterfaceInfoVO(InterfaceInfo interfaceInfo, HttpServletRequest request) {
        InterfaceInfoVO interfaceInfoVO = InterfaceInfoVO.objToVo(interfaceInfo);
        Long userId = interfaceInfo.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        // 获取脱敏后的用户信息
        UserVO userVO = userService.getUserVO(user);
        interfaceInfoVO.setUser(userVO);
        return interfaceInfoVO;
    }


    /**
     * 获取分页后的VO信息(之后补充)
     *
     * @param interfaceInfoPage
     * @param request
     * @return
     */
    @Override
    public Page<InterfaceInfoVO> getInterfaceInfoVOPage(Page<InterfaceInfo> interfaceInfoPage, HttpServletRequest request) {
        return null;
    }


}




